class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
}

public class Tree {
    public static void main(String[] args) {
        Tree tree = new Tree();
        TreeNode root = new TreeNode(2);
        TreeNode root3 = new TreeNode(3);
        TreeNode root4 = new TreeNode(4);
        TreeNode root5 = new TreeNode(5);
        TreeNode root6 = new TreeNode(6);

        root.left = null;
        root.right = root3;
        root3.left = null;
        root3.right = root4;
        root4.left = null;
        root4.right = root5;
        root5.left = null;
        root5.right = root6;
        root6.left = root6 = null;

        boolean ret = tree.isBalanced(root);
        System.out.println(ret);
    }
    public boolean isBalanced(TreeNode root) {
        return getHeight(root) >= 0 ? true : false;
    }
    private int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }
        //左子树已经非平衡
        int leftHeight = getHeight(root.left);
        if(leftHeight < 0) {
            return -1;
        }
        //右子树已经非平衡
        int rightHeight = getHeight(root.right);
        if(leftHeight < 0) {
            return -1;
        }
        //左右子树都是平衡树，左右子树高度差计算得出新高度
        if(Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        }
        return Math.max(leftHeight, rightHeight) + 1;
    }
}
